package com.yu.boot.admin.common.secure;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 拦截@Permission注解的方法进行权限验证
 * <p>
 * Created by hunan on 2017/5/21.
 */
@Component
@Slf4j
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if(handler instanceof HandlerMethod){
            request.getSession().setAttribute("ctx",request.getContextPath());
            Object user = request.getSession().getAttribute("user");
            String requestURI = request.getRequestURI();
            String replaceRquestURI = requestURI.replace(request.getContextPath(), "");
            AntPathMatcher antPathMatcher = new AntPathMatcher();
            List<String> strings = Arrays.asList("/", "/index", "/login*","/login/**","/category/collect*");
            for (int i = 0; i < strings.size(); i++) {
                if(antPathMatcher.match(strings.get(i), replaceRquestURI)){
                    return true;
                }
            }
            if (user == null) {
                try {
                    response.sendRedirect("login/view");
                } catch (IOException e) {
                    e.printStackTrace();
                }
//                forward("/login/login", request, response);
                return true;
            }
        }
        return true;
    }

    private void forward(String page, HttpServletRequest request, HttpServletResponse response) {
        RequestDispatcher rd = request.getRequestDispatcher(page);
        try {
            rd.forward(request, response);
        } catch (Exception e1) {
            log.error("", e1);
        }
    }


}